package cn.lsj.gateway.config;

import org.springframework.cloud.gateway.filter.ratelimit.KeyResolver;
import org.springframework.cloud.gateway.filter.ratelimit.RedisRateLimiter;
import org.springframework.cloud.gateway.route.RouteLocator;
import org.springframework.cloud.gateway.route.builder.RouteLocatorBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import reactor.core.publisher.Mono;

@Configuration
public class RedisRateLimiterConfig {

    @Bean
    public RedisRateLimiter redisRateLimiter() {
        return new RedisRateLimiter(10, 20); // 限制每秒最多10个请求，突发流量不超过20个请求
    }

    @Bean
    public RouteLocator customRouteLocator(RouteLocatorBuilder builder, RedisRateLimiter redisRateLimiter) {
        return builder.routes()
                .route("order_limiting_route", r -> r.path("/**")
                        .filters(f -> f.requestRateLimiter(c -> c.setRateLimiter(redisRateLimiter)))
                        .uri("forward:/currentLimiting"))
                .build();
    }

//    @Bean
//    public KeyResolver keyResolver(){
//        return exchange -> Mono.just(Objects.requireNonNull(exchange
//                        .getRequest()
//                        .getRemoteAddress())
//                .getHostName());
//    }

//    配置令牌桶算法的key:将主机名称作为限流key
    @Bean
    public KeyResolver keyResolver(){
        // 对请求的uri路径进行限流
        return exchange -> Mono.just(exchange
                .getRequest()
                .getURI()
                .getPath());
    }

}
